package org.csu.jpetstore_manage_system.web;

import org.csu.jpetstore_manage_system.domain.Order;
import org.csu.jpetstore_manage_system.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;

    private ModelAndView modelAndView = new ModelAndView();

    @GetMapping("/orders")
    public ModelAndView getAllOrder(){
        List<Order> orderList = orderService.getAllOrderList();
        modelAndView.addObject("orderList",orderList);
        modelAndView.setViewName("page/orders");
        return modelAndView;
    }

    @RequestMapping("/refreshOrder")
    public ModelAndView refreshOrder(@RequestParam("orderId") String orderId) {
        if (orderId.isEmpty())
            return getAllOrder();
        int orderid = Integer.parseInt(orderId);
        Order order = orderService.getOrderByOrderId(orderid);
        modelAndView.addObject("orderList", order);
        modelAndView.setViewName("page/orders");
        return modelAndView;
    }

    @RequestMapping("/deleteOrder")
    public ModelAndView deleteOrder(@RequestParam("orderId") int orderId) {
        orderService.deleteOrderById(orderId);
        return getAllOrder();
    }

    @RequestMapping("/toEdit")
    public ModelAndView toEdit(@RequestParam("orderId") int orderId) {
        Order order = orderService.getOrderByOrderId(orderId);
        modelAndView.addObject("order",order);
        modelAndView.setViewName("/page/orderEdit");
        return modelAndView;
    }

    @RequestMapping("/modifyOrder")
    public ModelAndView modifyOrder(
            @RequestParam("orderId") int orderId,
            @RequestParam("username") String username,
            @RequestParam("orderDate") Date orderDate,
            @RequestParam("shipAddress1") String shipAddress1,
            @RequestParam("totalPrice") BigDecimal totalPrice) {
        orderService.updateOrder(orderId, username, orderDate, shipAddress1, totalPrice);
        return getAllOrder();
    }

    @RequestMapping("/changeOrderStatus")
    public ModelAndView changeOrderStatus(@RequestParam("orderId") int orderId) {
        Order order = orderService.getOrderByOrderId(orderId);
        order.setStatus("P");
        orderService.updateOrderStatus(order);
        return getAllOrder();
    }
}
